package com.gao.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

public class CASDemo {



//    CAS compareAndSet : 比较并交换！
    public static void main(String[] args) {
//        AtomicInteger atomicInteger = new AtomicInteger(2020);
        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(22,1);

        new Thread(() -> {
//            获得版本号
            int stamp = atomicStampedReference.getStamp();
            System.out.println("A1 => " + stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println(atomicStampedReference.compareAndSet(22, 23,
                    atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));

            System.out.println("A2 => " + atomicStampedReference.getStamp());

            System.out.println(atomicStampedReference.compareAndSet(23, 22,
                    atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));

            System.out.println("A3 => " + atomicStampedReference.getStamp());

        },"A").start();

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println("B1 => " + stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println(atomicStampedReference.compareAndSet(22, 23,
                    stamp, stamp + 1));

            System.out.println("B2 => " + atomicStampedReference.getStamp());

        },"B").start();




//        对于我们平时写的sql ：乐观锁！

//        期望，更新
//        如果我期望的值达到了，就更新，否则不更新
//        =======捣乱线程======
//        System.out.println(atomicInteger.compareAndSet(2020, 2021));
//        System.out.println(atomicInteger);
//
//        System.out.println(atomicInteger.compareAndSet(2021, 2020));
//        System.out.println(atomicInteger);
//        =======捣乱线程======

//        =======期望线程======
//        System.out.println(atomicInteger.compareAndSet(2020, 6666));
//        System.out.println(atomicInteger);


    }
}
